package com.baomidou.springboot.helper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.springboot.service.impl.HtmlFetchServiceImpl;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zcy on 2017/7/10.
 */
public class DescCatoryHelper {
    protected static Logger logger = Logger.getLogger(HtmlFetchServiceImpl.class);
    public static long startTime=0L;
    private static Map<String,String> cookies=new HashMap<String, String>();
    public static String cookieValue="cna=tga8EbBcvXMCAT2kLOIAUaEW; JSESSIONID=9L78akHi1-UTuXiEthutRMvitEX6-n3QzANQ-5; ali_apache_tracktmp=c_w_signed=Y; UM_distinctid=15ce2219995513-00d8cba4ea4315-30637509-fa000-15ce2219998335; ali_ab=61.164.44.227.1498442470640.7; ali_beacon_id=125.119.97.245.1499350606582.345152.8; __utma=62251820.2072789624.1498039596.1499649836.1499687296.12; __utmc=62251820; __utmz=62251820.1499687296.12.4.utmcsr=fuwu.1688.com|utmccn=(referral)|utmcmd=referral|utmcct=/; cookie1=VWn702wpzyh3k5ahnn0hZxYMCd02r7FMdjsshwhjVrY%3D; cookie2=1c54510eb7f68ae9d16bfdfdc56f378c; cookie17=Uoe2zs0v%2F6x2yQ%3D%3D; hng=CN%7Czh-CN%7CCNY; uss=Aia0cJNmEgAIOUqSMjWgzbdxiNAWCKxEq%2FGMamm0czn0w5iZbObseLLNm2Y%3D; t=0679cabbfa957448f2686b7c77adc54d; _tb_token_=hm16iL8fgttdX5; sg=154; m_id=b2b-1623492085; m_level=PM; m_sign=15033040909; __cn_logon__=true; __cn_logon_id__=alitestforisv01; ali_apache_track=c_ms=2|c_mt=3|c_mid=b2b-1623492085|c_lid=alitestforisv01; cn_tmp=Z28mC+GqtZ3NJkA74i0LmXwopqGKU5eX6yNpIAx4DSx6XVYZ9mTMMokyj8CZcUy5Mpw8PqPyRGtvO08e0RqvUxaXAh1cFqmhO271JCTbNiQxfoo91wY7Q8usWUlMKk59iV/4zvCPlbPSjR6lSQLQp8uqCSrRbEfvN5t/Lc+vYOdSTkQgZoOZ19d9BNWTSzu4bygq/gjlaBG7zg/l8XwhTX3v2zo9ZPkO/kpEAkpud9VswXFTXFQzKmBMcJZIZq4y; _cn_slid_=Yw77U%2Faevo; tbsnid=HpUGYhtMs%2BLRqKu8BXdiv9KnL2EQJK0UwGZGZZcvBz46sOlEpJKl9g%3D%3D; LoginUmid=okboxHiH%2BNnymw6bMzdHDuvYtHgURhnlfwmlW8OKvwJ0ZvS19%2BaAOg%3D%3D; userID=ErBDlm7903Usue5a710T1MglkS5l96nSeVZxwVRavgo6sOlEpJKl9g%3D%3D; last_mid=b2b-1623492085; unb=1623492085; __last_loginid__=alitestforisv01; login=kFeyVBJLQQI%3D; _csrf_token=1499740652730; _is_show_loginId_change_block_=b2b-1623492085_false; _show_force_unbind_div_=b2b-1623492085_false; _show_sys_unbind_div_=b2b-1623492085_false; _show_user_unbind_div_=b2b-1623492085_false; __rn_alert__=false; alicnweb=touch_tb_at%3D1499739955076%7Clastlogonid%3Dalitestforisv01%7Cshow_inter_tips%3Dfalse; isg=AgMDdv0oXg740xLUYA2L6d4FksGnHJUFSvIddjXgUGLZ9CMWvUgnCuFmGLJB; userIDNum=SMpaEUPYMU5DvHK82Tv9Og%3D%3D; _tmp_ck_0=Us6kfQ%2FxEOMYxhQl3h8Zy2qS7TsgfERBwsaPKUWJcc0y4D%2BFOeBUxAroIEq0%2BQ4afxF7wyoJLRXQGBBkkw2c39mxwR2n%2B0hpYixZDH9Kar0tz%2ByBa6%2FqYdKgVh%2FVsdR4oAiP5hrphnxokTYjrhkg35B3DocbjakY4bO2CzJf6fwGnBvVe4XR%2FKeLSGChepHjGxp4BIgrXbVOJifHqEWlmaf6aZzRnED6pS1Bm3LFrE6nvkZUa2rUQlo0%2FKSTDQ%2BRBp4An2P82tlCe8OFLnKZDE0t5NfLg%2Btmvrh6bCU97cZoSDyhpD1gCUQ1DvCL0%2B6Xvv3e1C1zHE%2FcGvgoFeDdZKzIvo08W5byCCWboFybBKchAhTjuE9tdrtYO8uuHr8prcFDLUGtgj4ubkkyVB8tMB5j1jSvCcPoVd7I3w0cCTPGn9ORbue5%2B%2FhDdqUY7qRLKbfUeP7X21Ifk%2Ba1KEPgn%2Bq3pwbneUw7R3OPt%2Bs2ozhtwfkqKyvN9OaDxdg3icbxpx%2Bo8H%2FxfXuaYJdg8BpwwAQ897EhhHaOw4EIyhBCY4Rv0C8ImRyxTA%3D%3D; _nk_=LqvxMzrmw3PVQ3A%2BS4htCA%3D%3D";
    static{
        String[] arr=cookieValue.split(";");
        for(String cookiestr:arr){
            String[] cookiearr=cookiestr.split("=");
            if(cookiearr.length==2){
                cookies.put(cookiearr[0], cookiearr[1]);
            }else{
                cookies.put(cookiearr[0], "");
            }

        }
    }

    /**
     * ajax请求详情页面
     * @param doc
     */
    public static boolean requestDesc(Document doc){
        String modDetailDescription = doc.select("#mod-detail-description").attr("data-mod-config");
        HashMap modMap = JSON.parseObject(modDetailDescription, HashMap.class);
        JSONArray catalog = (JSONArray)modMap.get("catalog");
        if(catalog!=null){
            catalog(catalog,doc);
            return true;
        }
        String url = doc.select("#desc-lazyload-container").attr("data-tfs-url");
        if(url!=null){
            tfsUrl(url,doc);
            return true;
        }
        return false;
        //throw new Exception(String.format("解析不到详情页%s",url));

    }

    private static void catalog(JSONArray catalog,Document doc){
        JSONObject desc=(JSONObject)catalog.get(0);
        if(desc.containsKey("contentUrl")){
            String contentUrl = (String) desc.get("contentUrl");
            Document descDoc = parseUrl(contentUrl);
            String bodyhtml = descDoc.body().html();
            String content = bodyhtml.substring(30, bodyhtml.length() - 3);
            content=content.replaceAll("\\\\&quot;","");
            //content = StringEscapeUtils.unescapeHtml4(content);
            Element modEle= doc.select("#desc-lazyload-container").first();
            modEle.html(content);
        }
    }

    private static void tfsUrl(String url,Document doc){
        Document descDoc = parseUrl(url);
        String bodyhtml = descDoc.body().html();
        String content = bodyhtml.substring(10, bodyhtml.length() - 2);
        Element modEle= doc.select("#desc-lazyload-container").first();
        modEle.html(content);
    }

    private static Document parseUrl(String url){
        Document doc =null;
        try {
            doc = Jsoup.connect(url).cookies(cookies).header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0").timeout(20000).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return doc;
    }

    public static void main(String[] args) {

    }

}
